/**
 * 得到字符串的哈希值
 * @param {string} str
 * @returns {number}
 */
const hashCode = str => {
  let hash = 0, i, chr;
  if (str.length === 0 || typeof(str) !== 'string') return hash;
  for (i = 0; i < str.length; i++) {
    chr   = str.charCodeAt(i);
    hash  = ((hash << 5) - hash) + chr;
    hash |= 0; // Convert to 32bit integer
  }
  return hash;
};
/**
 * @returns {string}
 */
const createUniqueString = () => {
  const timestamp = +new Date() + '';
  const randomNum = parseInt((1 + Math.random()) * 65536) + '';
  return (+(randomNum + timestamp)).toString(32);
};
/**
 * 对关系查询结果key重新拼接，只返回修改过的对象数组
 * @parm {array} result
 * @parm {string} field
 * @parm {array} attribute
 * @returns {array}
 */
const getResultToObject = (result, field, attribute) => {
  const list = [];
  for (const obj of result) {
    const config = {};
    for (const item of attribute) {
      if (!obj[field + '.' + item]) return list;
      else config[item] = obj[field + '.' + item];
    }
    list.push(config);
  }
  return list;
};

/**
 * 对关系查询结果key重新拼接，返回完整数组
 * @parm {array} result
 * @parm {string} field
 * @parm {array} attribute
 * @returns {array}
 */
const getResultToObjectComplete = (result, field, attribute) => {
  const list = [];
  for (const json of result) {
    const config = {};
    for (const key in json) {
      if (json.hasOwnProperty(key) && key.indexOf('.') < 0) config[key] = json[key];
      else {
        for (const item of attribute) {
          if (json[field + '.' + item]) config[item] = json[field + '.' + item];
        }
      }
    }
    list.push(config);
  }
  return list;
};


module.exports = {
  hashCode,
  getResultToObject,
  createUniqueString,
  getResultToObjectComplete
};

